import http  from "http";
import url from"url"
export default class WebServer {


    run(port,index,staticPath) {

        let strtIndex=new Index();
        if(staticPath){
            let Static=qguan("Static");
            let  _static =new Static(staticPath);
            qguan("static",_static,null,"save");
        }

        if(index){
            strtIndex=qguan(index);

        }


        let parsePostBody = function (req, done) {
            let length = req.headers['content-length'] - 0;
            let arr = [];
            let chunks;

            req.on('data', buff => {
                arr.push(buff);
            });
            req.on('end', () => {
                chunks = Buffer.concat(arr);
                done(chunks);
            });
        };

       let server= http.createServer(function(request,res){

            // 获取请求主体内容
            /*     req.on('data', function (thunk) {

                   });*/
           res.setHeader("Access-Control-Allow-Origin", "*");

            try {
                let req = url.parse(request.url,true);
                debugger
                if(req.pathname=="/"){
                    strtIndex.run(request,res,req);
                }

                if(request.method=='GET'){
                    // 解析请求，包括文件名
                    qguan(request,res,req,"HttpContex")
                }else {

                    res.setHeader("Content-Type", "application/json;charset=utf-8");
                    parsePostBody(request, (chunkss) => {
                        if(chunkss.length>0){
                            request.body= JSON.parse( chunkss.toString() );  // 关键代码
                        }
                        qguan(request,res,req,"HttpContex")
                    })
                }
            }catch (e) {
                //打印出错误的调用栈方便调试
                console.log(e.stack);
            }



        });
       let lang=8*1204*1204;
        server.maxHeadersCount=lang;
        server .listen(port);
    }

}


class  Index{
    run(request,res,req){
        let code= "欢迎使用 qguan Web Server ";
        res.write(code)
        res.end();
    }
}
